{% extends "base.html" %}

{% block head %}
<style>
    :root {
        --primary-color: #1976d2;
        --primary-hover: #1565c0;
        --border-color: #e0e0e0;
        --light-gray: #f5f5f5;
        --text-color: #333;
        --shadow-color: rgba(0, 0, 0, 0.1);
    }

    body {
        color: var(--text-color);
        background-color: #f8f9fa;
    }

    .container {
        min-width: 800px;
        margin: 0 auto;
    }

    /* 卡片样式 */
    .card {
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 4px var(--shadow-color);
        padding: 20px;
        margin-bottom: 20px;
    }

    .card-header {
        margin: -20px -20px 20px;
        padding: 15px 20px;
        background: var(--light-gray);
        border-radius: 8px 8px 0 0;
        border-bottom: 1px solid var(--border-color);
    }

    .card-header h2 {
        margin: 0;
        font-size: 1.5rem;
        color: var(--primary-color);
    }

    .card-header .card-header_text {
        font-size: 12px;
        font-weight: 400;
        color: rgba(128, 128, 128, 1);
    }

    /* 表格容器样式优化 */
    .table-wrapper {
        position: relative;
        background: white;
    }

    .table-container {
        width: 100%;
        overflow-x: auto;
        position: relative;
        max-height: 600px;
        overflow-y: auto;
        scrollbar-width: thin;
        scrollbar-color: var(--primary-color) var(--light-gray);
    }

    /* 自定义滚动条样式 */
    .table-container::-webkit-scrollbar {
        width: 8px;
        height: 8px;
    }

    .table-container::-webkit-scrollbar-track {
        background: var(--light-gray);
        border-radius: 4px;
    }

    .table-container::-webkit-scrollbar-thumb {
        background: var(--primary-color);
        border-radius: 4px;
    }

    .table-container::-webkit-scrollbar-thumb:hover {
        background: var(--primary-hover);
    }

    /* 滑动指示器 */
    .scroll-indicator {
        position: absolute;
        right: 10px;
        top: 50%;
        transform: translateY(-50%);
        background: rgba(0, 0, 0, 0.5);
        color: white;
        padding: 8px;
        border-radius: 4px;
        font-size: 12px;
        opacity: 0;
        transition: opacity 0.3s;
        pointer-events: none;
        z-index: 99;
    }

    .scroll-indicator.visible {
        opacity: 1;
    }

    /* 表格样式优化 */
    .result-table {
        width: 100%;
        border-collapse: separate;
        border-spacing: 0;
        margin: 0;
        font-size: 12px;
        min-width: 1200px;
    }

    .result-table th {
        background: #e6f7ff;
        color: #0050b3;
        font-weight: normal;
        position: sticky;
        top: 0;
        z-index: 1;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        min-width: 120px;
        padding: 8px 6px;
        line-height: 1.4;
    }

    .result-table th:hover {
        overflow: visible;
        white-space: nowrap;
        background: #e6f7ff;
        position: relative;
        z-index: 3;
    }

    .result-table td {
        border: 1px solid #d9d9d9;
        padding: 6px 4px;
        text-align: left;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 150px;
    }

    .result-table tr:nth-child(even) {
        background: #f5faff;
    }

    .result-table td:hover {
        overflow: visible;
        white-space: normal;
        word-break: break-all;
        position: relative;
        z-index: 2;
        background: #fff;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }

    /* 分页控件美化 */
    .pagination-container {
        background: white;
        padding: 15px;
        border-top: 1px solid var(--border-color);
        border-radius: 0 0 8px 8px;
        display: flex;
        justify-content: flex-end;
        margin-top: 12px;
        gap: 8px;
    }

    #total-records {
        color: #555;
        font-size: 13px;
        margin-right: 16px;
    }

    .pagination {
        display: flex;
        justify-content: center;
        gap: 8px;
    }

    .pagination button {
        padding: 4px 12px;
        border: 1px solid #d9d9d9;
        border-radius: 4px;
        background: #fff;
        cursor: pointer;
    }

    .pagination button:disabled {
        background: #f5f5f5;
        cursor: not-allowed;
    }

    .pagination button.active {
        background: #1890ff;
        color: white;
        border-color: #1890ff;
    }

    .pagination-ellipsis {
        color: #555;
        padding: 0 8px;
    }

    /* 表单样式优化 */
    .form-group {
        margin-bottom: 20px;
    }

    .form-label {
        display: block;
        margin-bottom: 8px;
        font-weight: 500;
    }

    .form-control {
        width: 100%;
        padding: 8px 12px;
        border: 1px solid var(--border-color);
        border-radius: 4px;
        font-size: 14px;
    }

    .checkbox-group {
        display: flex;
        flex-wrap: wrap;
        gap: 12px;
        padding: 10px;
        background-color: var(--light-gray);
        border-radius: 4px;
    }

    .checkbox-item {
        min-width: 120px;
        display: flex;
        align-items: center;
    }

    .form-check-input {
        margin-right: 6px;
    }

    .form-check-label {
        font-size: 14px;
        user-select: none;
    }

    .btn {
        display: inline-block;
        padding: 8px 16px;
        font-size: 14px;
        font-weight: 500;
        text-align: center;
        text-decoration: none;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.2s;
        border: 1px solid transparent;
    }

    .btn-primary {
        background-color: var(--primary-color);
        color: white;
        border: none;
    }

    .btn-primary:hover {
        background-color: var(--primary-hover);
    }

    .btn-outline-primary {
        background-color: transparent;
        border-color: var(--primary-color);
        color: var(--primary-color);
    }

    .btn-outline-primary:hover {
        background-color: var(--primary-color);
        color: white;
    }

    .btn-sm {
        padding: 4px 12px;
        font-size: 12px;
    }

    .select-all-btn {
        margin-bottom: 10px;
    }

    /* 加载动画 */
    .loading {
        display: none;
        text-align: center;
        margin: 20px 0;
    }

    .loading.active {
        display: block;
    }

    /* 错误消息 */
    .error-message {
        color: red;
        margin: 10px 0;
        display: none;
    }

    /* 下载按钮 */
    .download-btn {
        margin-top: 10px;
        display: none;
    }

    /* 字段选择样式 */
    .field-selection {
        margin: 20px 0;
        padding: 15px;
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 4px var(--shadow-color);
        display: none;
    }

    .field-selection.visible {
        display: block;
    }

    .field-selection-title {
        font-weight: 600;
        margin-bottom: 10px;
        color: var(--primary-color);
    }

    .field-selection-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
        gap: 10px;
        margin-top: 10px;
    }

    .field-checkbox {
        display: flex;
        align-items: center;
        padding: 8px;
        background: var(--light-gray);
        border-radius: 4px;
        cursor: pointer;
        transition: background-color 0.2s;
    }

    .field-checkbox:hover {
        background-color: var(--menu-hover);
    }

    .field-checkbox input {
        margin-right: 8px;
    }

    /* 按钮组样式 */
    .button-group {
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .button-group > * {
        margin: 0 !important;
    }

    /* 模态框样式 */
    .modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        z-index: 1000;
    }

    .modal.visible {
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .modal-content {
        background-color: white;
        padding: 24px;
        border-radius: 8px;
        width: 90%;
        max-width: 800px;
        max-height: 90vh;
        overflow-y: auto;
        position: relative;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }

    .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        padding-bottom: 16px;
        border-bottom: 1px solid var(--border-color);
    }

    .modal-title {
        font-size: 20px;
        font-weight: 600;
        color: var(--text-color);
        margin: 0;
    }

    .modal-close {
        background: none;
        border: none;
        font-size: 24px;
        color: var(--text-color);
        cursor: pointer;
        padding: 4px;
        line-height: 1;
    }

    .modal-close:hover {
        color: var(--primary-color);
    }

    .modal-body {
        margin-bottom: 20px;
    }

    .modal-footer {
        display: flex;
        justify-content: flex-end;
        gap: 12px;
        padding-top: 16px;
        border-top: 1px solid var(--border-color);
    }

    /* 字段选择按钮 */
    .field-select-btn {
        margin-left: 12px;
    }
</style>
{% endblock %}

{% block content %}
<div class="container">
    <div class="card">
        <div class="card-header">
            <h2>住宿天数为偶数但住宿费为奇数模型</h2>
            <div class="card-header_text">
                模型重点关注是否存在多开、虚报住宿费的问题。通过关联《差旅费票据信息》与《差旅报销行程明细》，将发票金额、住宿天数按照奇数和偶数分类，筛选住宿天数为偶数、住宿发票金额为奇数的报销单，
                核实是否存在多开、虚报住宿费的情况。
            </div>
        </div>
        
        <form id="analysisForm">
            <!-- 隐藏的文件夹路径输入 -->
            <input type="hidden" id="folderPath" name="folderPath" required>

            <!-- 年度选择 -->
            <div class="form-group">
                <label class="form-label">选择查询年度（可多选）：</label>
                <button type="button" class="btn btn-outline-primary btn-sm select-all-btn" onclick="toggleSelectAll('years')">全选/取消全选</button>
                <div class="checkbox-group" id="years">
                    <!-- 年度选项将通过JavaScript动态生成 -->
                </div>
            </div>

            <!-- 提交按钮 -->
            <div class="form-group">
                <div class="button-group">
                    <button type="submit" class="btn btn-primary">立即输出</button>
                    <button type="button" class="btn btn-outline-primary field-select-btn" onclick="openFieldSelection()" style="display: none;">选择字段</button>
                    <a href="/download-even-odd-excel" class="btn btn-outline-primary download-btn" id="downloadBtn" style="display: none;">下载Excel</a>
                </div>
            </div>
        </form>

        <!-- 错误消息 -->
        <div id="errorMessage" class="error-message"></div>

        <!-- 加载动画 -->
        <div id="loading" class="loading">
            <div class="loading-spinner"></div>
            正在分析数据，请稍候...
        </div>
    </div>

    <!-- 结果表格 -->
    <div id="resultContainer" class="card" style="display: none;">
        <div class="table-wrapper">
            <div class="scroll-indicator">向右滑动查看更多</div>
            <div class="table-container">
                <table class="result-table">
                    <thead>
                        <tr id="tableHeader">
                            <!-- 表头将通过JavaScript动态生成 -->
                        </tr>
                    </thead>
                    <tbody id="tableBody">
                        <!-- 数据行将通过JavaScript动态生成 -->
                    </tbody>
                </table>
            </div>
            <div class="pagination-container">
                <div class="pagination" id="pagination"></div>
            </div>
        </div>
    </div>

    <!-- 字段选择模态框 -->
    <div id="fieldSelectionModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">选择显示字段</h3>
                <button type="button" class="modal-close" onclick="closeFieldSelection()">&times;</button>
            </div>
            <div class="modal-body">
                <button type="button" class="btn btn-outline-primary btn-sm select-all-btn" onclick="toggleSelectAllFields()">全选/取消全选</button>
                <div class="field-selection-grid" id="fieldCheckboxes">
                    <!-- 字段选择项将通过JavaScript动态生成 -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-primary" onclick="closeFieldSelection()">取消</button>
                <button type="button" class="btn btn-primary" onclick="applyAndCloseFieldSelection()">确定</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    // 生成年度选项（当前年份往前10年）
    const yearsDiv = document.getElementById('years');
    const currentYear = new Date().getFullYear();
    for (let year = currentYear; year >= currentYear - 10; year--) {
        const div = document.createElement('div');
        div.className = 'checkbox-item';
        div.innerHTML = `
            <input type="checkbox" class="form-check-input" id="year_${year}" name="years" value="${year}">
            <label class="form-check-label" for="year_${year}">${year}</label>
        `;
        yearsDiv.appendChild(div);
    }

    // 全选/取消全选功能
    function toggleSelectAll(groupId) {
        const container = document.getElementById(groupId);
        const checkboxes = container.querySelectorAll('input[type="checkbox"]');
        const allChecked = Array.from(checkboxes).every(cb => cb.checked);
        
        checkboxes.forEach(checkbox => {
            checkbox.checked = !allChecked;
        });
    }

    // 页面加载时设置文件夹路径
    window.addEventListener('DOMContentLoaded', () => {
        const savedPath = localStorage.getItem('globalFolderPath');
        if (savedPath) {
            document.getElementById('folderPath').value = savedPath;
        }
    });

    // 当前页码和数据缓存
    let currentPage = 1;
    let totalPages = 1;
    let cachedFormData = null;
    let isLoading = false;

    // 处理表单提交
    document.getElementById('analysisForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        
        if (isLoading) return;
        
        document.getElementById('loading').classList.add('active');
        document.getElementById('errorMessage').style.display = 'none';
        document.getElementById('resultContainer').style.display = 'none';
        document.getElementById('downloadBtn').style.display = 'none';
        document.querySelector('.field-select-btn').style.display = 'none';
        
        isLoading = true;
        
        try {
            cachedFormData = new FormData(e.target);
            cachedFormData.append('page', currentPage);
            cachedFormData.append('folderPath', 'data');

            // 添加选中的字段到表单数据
            if (selectedFields.length > 0) {
                selectedFields.forEach(field => {
                    cachedFormData.append('fields', field.id);
                });
            }

            const response = await fetch('/analyze-even-odd', {
                method: 'POST',
                body: cachedFormData
            });

            const result = await response.json();

            if (!response.ok) {
                document.getElementById('errorMessage').textContent = '没有找到符合条件的数据';
                document.getElementById('errorMessage').style.display = 'block';
                return;
            }

            displayResults(result);
            document.getElementById('downloadBtn').style.display = 'inline-block';
        } catch (error) {
            document.getElementById('errorMessage').textContent = '没有找到符合条件的数据';
            document.getElementById('errorMessage').style.display = 'block';
        } finally {
            document.getElementById('loading').classList.remove('active');
            isLoading = false;
        }
    });

    // 切换页面
    async function changePage(page) {
        if (page < 1 || page > totalPages || isLoading) return;
        
        const tableBody = document.getElementById('tableBody');
        tableBody.style.opacity = '0.5';
        document.getElementById('errorMessage').style.display = 'none';
        
        isLoading = true;
        currentPage = page;

        try {
            const formData = new FormData();
            for (let [key, value] of cachedFormData.entries()) {
                if (key !== 'page') {
                    formData.append(key, value);
                }
            }
            formData.append('page', currentPage);

            // 添加选中的字段到表单数据
            selectedFields.forEach(field => {
                formData.append('fields', field.id);
            });

            const response = await fetch('/analyze-even-odd', {
                method: 'POST',
                body: formData
            });

            const result = await response.json();

            if (!response.ok) {
                document.getElementById('errorMessage').textContent = '没有找到符合条件的数据';
                document.getElementById('errorMessage').style.display = 'block';
                return;
            }

            updateTableContent(result);
            updatePagination();
        } catch (error) {
            document.getElementById('errorMessage').textContent = '没有找到符合条件的数据';
            document.getElementById('errorMessage').style.display = 'block';
        } finally {
            tableBody.style.opacity = '1';
            isLoading = false;
        }
    }

    // 更新表格内容
    function updateTableContent(result) {
        const tableBody = document.getElementById('tableBody');
        tableBody.innerHTML = '';

        // 显示数据
        result.data.forEach(row => {
            const tr = document.createElement('tr');
            selectedFields.forEach(field => {
                if (row.hasOwnProperty(field.id)) {
                    const td = document.createElement('td');
                    const value = row[field.id];
                    
                    if (typeof value === 'number') {
                        td.className = 'number';
                        if (field.id === '发票含税金额' || field.id === '本位币金额' || 
                            field.id === '不含税金额' || field.id === '可分摊金额' || 
                            field.id === '税值' || field.id === '增值税' || 
                            field.id === '发票金额' || field.id === '发票税额') {
                            td.textContent = value.toFixed(2);
                        } else if (field.id === '住宿天数' || field.id === '年度' || 
                                 field.id === '发票张数') {
                            td.textContent = Math.round(value);
                        } else {
                            td.textContent = value;
                        }
                    } else {
                        td.textContent = value || '-';
                    }
                    
                    tr.appendChild(td);
                }
            });
            tableBody.appendChild(tr);
        });

        // 更新分页信息
        totalPages = result.total_pages;
        currentPage = result.current_page;
    }

    // 显示结果函数
    function displayResults(result) {
        const container = document.getElementById('resultContainer');
        const tableHeader = document.getElementById('tableHeader');
        const tableBody = document.getElementById('tableBody');
        const fieldSelectBtn = document.querySelector('.field-select-btn');

        // 清空现有内容
        tableHeader.innerHTML = '';
        tableBody.innerHTML = '';

        if (result.data.length === 0) {
            document.getElementById('errorMessage').textContent = '没有找到符合条件的数据';
            document.getElementById('errorMessage').style.display = 'block';
            return;
        }

        // 更新可用字段列表
        availableFields = result.all_columns.map(column => ({
            id: column,
            name: column
        }));

        // 如果是首次加载数据或切换了维度，初始化选中所有字段
        if (selectedFields.length === 0) {
            selectedFields = [...availableFields];
        }

        // 显示字段选择按钮
        fieldSelectBtn.style.display = 'inline-block';

        // 生成表头
        selectedFields.forEach(field => {
            const th = document.createElement('th');
            th.textContent = field.name;
            tableHeader.appendChild(th);
        });

        // 显示数据
        result.data.forEach(row => {
            const tr = document.createElement('tr');
            selectedFields.forEach(field => {
                if (row.hasOwnProperty(field.id)) {
                    const td = document.createElement('td');
                    const value = row[field.id];
                    
                    if (typeof value === 'number') {
                        td.className = 'number';
                        if (field.id === '发票含税金额' || field.id === '本位币金额' || 
                            field.id === '不含税金额' || field.id === '可分摊金额' || 
                            field.id === '税值' || field.id === '增值税' || 
                            field.id === '发票金额' || field.id === '发票税额') {
                            td.textContent = value.toFixed(2);
                        } else if (field.id === '住宿天数' || field.id === '年度' || 
                                 field.id === '发票张数') {
                            td.textContent = Math.round(value);
                        } else {
                            td.textContent = value;
                        }
                    } else {
                        td.textContent = value || '-';
                    }
                    
                    tr.appendChild(td);
                }
            });
            tableBody.appendChild(tr);
        });

        // 更新分页信息
        totalPages = result.total_pages;
        currentPage = result.current_page;
        
        // 更新分页控件
        updatePagination();

        // 显示结果容器
        container.style.display = 'block';

        // 添加滑动指示器逻辑
        setTimeout(() => {
            const tableContainer = document.querySelector('.table-container');
            const scrollIndicator = document.querySelector('.scroll-indicator');
            
            if (tableContainer && scrollIndicator) {
                const hasHorizontalScroll = tableContainer.scrollWidth > tableContainer.clientWidth;
                scrollIndicator.classList.toggle('visible', hasHorizontalScroll);
                
                tableContainer.addEventListener('scroll', () => {
                    const isScrolledRight = tableContainer.scrollLeft + tableContainer.clientWidth >= tableContainer.scrollWidth;
                    scrollIndicator.classList.toggle('visible', hasHorizontalScroll && !isScrolledRight);
                });
            }
        }, 100);
    }

    // 更新分页控件
    function updatePagination() {
        const pagination = document.getElementById('pagination');
        pagination.innerHTML = '';

        // 如果总页数小于2，不显示分页
        if (totalPages < 2) return;

        // 上一页按钮
        const prevButton = document.createElement('button');
        prevButton.textContent = '上一页';
        prevButton.disabled = currentPage === 1;
        prevButton.onclick = () => changePage(currentPage - 1);
        pagination.appendChild(prevButton);

        // 计算需要显示的页码范围
        let startPage = Math.max(1, currentPage - 2);
        let endPage = Math.min(totalPages, startPage + 4);
        
        // 调整startPage确保显示5个页码
        startPage = Math.max(1, endPage - 4);

        // 添加第一页
        if (startPage > 1) {
            addPageButton(1);
            if (startPage > 2) {
                addEllipsis();
            }
        }

        // 添加中间的页码
        for (let i = startPage; i <= endPage; i++) {
            addPageButton(i);
        }

        // 添加最后一页
        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                addEllipsis();
            }
            addPageButton(totalPages);
        }

        // 下一页按钮
        const nextButton = document.createElement('button');
        nextButton.textContent = '下一页';
        nextButton.disabled = currentPage === totalPages;
        nextButton.onclick = () => changePage(currentPage + 1);
        pagination.appendChild(nextButton);

        // 辅助函数：添加页码按钮
        function addPageButton(pageNum) {
            const pageButton = document.createElement('button');
            pageButton.textContent = pageNum;
            pageButton.classList.toggle('active', pageNum === currentPage);
            pageButton.onclick = () => changePage(pageNum);
            pagination.appendChild(pageButton);
        }

        // 辅助函数：添加省略号
        function addEllipsis() {
            const ellipsis = document.createElement('span');
            ellipsis.textContent = '...';
            ellipsis.className = 'pagination-ellipsis';
            pagination.appendChild(ellipsis);
        }
    }

    // 定义可选字段及其显示名称
    let availableFields = [];

    // 当前选中的字段
    let selectedFields = [
        {id:"年度", name:"年度"},{id:"组织机构名称", name:"组织机构名称"},{id:"发票人员名称", name:"发票人员名称"},{id:"城市名称", name:"城市名称"},
        {id:"宾馆", name:"宾馆"},{id:"住宿天数", name:"住宿天数"},{id:"发票金额", name:"发票金额"},{id:"发票税额", name:"发票税额"},{id:"发票含税金额", name:"发票含税金额"},
        {id:"发票金额/发票含税金额都不为整数", name:"发票金额/发票含税金额都不为整数"}
    ];
    // let selectedFields = [
    //     {name:"年度"},{name:"组织机构名称"},{name:"发票人员名称"},{name:"城市名称"},{name:"宾馆"},{name:"住宿天数"},{name:"发票金额"},{name:"发票税额"},{name:"发票含税金额"},
    //     {name:"住宿天数偶数发票金额奇数"}
    // ];

    // 初始化字段选择
    function initializeFieldSelection() {
        const container = document.getElementById('fieldCheckboxes');
        container.innerHTML = '';
        
        if (cachedFormData) {
            const formData = new FormData();
            for (let [key, value] of cachedFormData.entries()) {
                if (key !== 'page') {
                    formData.append(key, value);
                }
            }
            formData.append('page', 1);

            fetch('/analyze-even-odd', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(result => {
                if (result.all_columns) {
                    // 更新可用字段
                    availableFields = result.all_columns.map(column => ({
                        id: column,
                        name: column
                    }));
                    
                    // 如果selectedFields为空，初始化为所有字段
                    if (selectedFields.length === 0) {
                        selectedFields = [...availableFields];
                    }
                    
                    // 创建复选框
                    availableFields.forEach(field => {
                        const div = document.createElement('div');
                        div.className = 'field-checkbox';
                        div.innerHTML = `
                            <input type="checkbox" id="field_${field.id}" name="fields" value="${field.id}" 
                                   ${selectedFields.find(f => f.id === field.id) ? 'checked' : ''}>
                            <label for="field_${field.id}">${field.name}</label>
                        `;
                        container.appendChild(div);
                    });
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });
        }
    }

    // 全选/取消全选字段
    function toggleSelectAllFields() {
        const checkboxes = document.querySelectorAll('#fieldCheckboxes input[type="checkbox"]');
        const allChecked = Array.from(checkboxes).every(cb => cb.checked);
        checkboxes.forEach(checkbox => checkbox.checked = !allChecked);
    }

    // 应用字段选择
    function applyFieldSelection() {
        const checkboxes = document.querySelectorAll('#fieldCheckboxes input[type="checkbox"]:checked');
        selectedFields = Array.from(checkboxes).map(cb => {
            const field = availableFields.find(f => f.id === cb.value);
            return field;
        });
        
        if (selectedFields.length === 0) {
            alert('请至少选择一个字段');
            return;
        }
        
        // 重新显示数据
        if (cachedFormData) {
            document.getElementById('analysisForm').dispatchEvent(new Event('submit'));
        }
    }

    // 重置字段选择
    function resetFieldSelection() {
        selectedFields = [...availableFields];
        initializeFieldSelection();
        if (cachedFormData) {
            document.getElementById('analysisForm').dispatchEvent(new Event('submit'));
        }
    }

    // 打开字段选择模态框
    function openFieldSelection() {
        const modal = document.getElementById('fieldSelectionModal');
        modal.classList.add('visible');
        initializeFieldSelection();
    }

    // 关闭字段选择模态框
    function closeFieldSelection() {
        const modal = document.getElementById('fieldSelectionModal');
        modal.classList.remove('visible');
    }

    // 应用选择并关闭模态框
    function applyAndCloseFieldSelection() {
        applyFieldSelection();
        closeFieldSelection();
    }
</script>
{% endblock %} 